package com.yunban.project.api.text_check.service.impl;

import com.alibaba.fastjson.JSON;
import com.yunban.project.api.text_check.domain.CorrectionConfig;
import com.yunban.project.api.text_check.dto.deepseek.ChatMessage;
import com.yunban.project.api.text_check.dto.deepseek.ChatResp;
import com.yunban.project.api.text_check.service.AiCorrectionService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.base.common.exception.BusinessException;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: lijiajun
 * @date: 2025-03-13
 * @version: 1.0
 */
@Slf4j
@Service("deepSeekGFService")
public class DeepSeekGFService implements AiCorrectionService {

    @Resource
    private RestTemplate restTemplate;

    @Override
    public String correction(String text, CorrectionConfig config, String taskId) {
        // 构建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(config.getApiKey());
        // 构造请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", config.getAiModel());
        requestBody.put("messages", Collections.singletonList(
                Map.of("role", "user", "content", config.getPromptPrefix() + text)
        ));
        requestBody.put("stream", false);
        try {
            ResponseEntity<ChatResp> response = this.restTemplate.exchange(
                    config.getUrlPath(),
                    HttpMethod.POST,
                    new HttpEntity<>(requestBody, headers),
                    ChatResp.class
            );
            log.info("DEEPSEEK API请求结果1：{}", JSON.toJSONString(response));
            // 解析响应结果
            if (response.getStatusCode().is2xxSuccessful()) {
                ChatResp chatResp = response.getBody();
                log.info("DEEPSEEK API请求结果2：{}", JSON.toJSONString(chatResp));
                if (ObjectUtils.isEmpty(chatResp)) {
                    return null;
                }
                List<ChatResp.Choice> choices = chatResp.getChoices();
                log.info("DEEPSEEK API请求结果3：{}", JSON.toJSONString(choices));
                if (!CollectionUtils.isEmpty(choices)) {
                    ChatMessage message = choices.get(0).getMessage();
                    if (!ObjectUtils.isEmpty(message)) {
                        String result = message.getContent();
                        if (!result.contains("输出：") && !result.contains("分类：") && !result.contains("来源：") && !result.contains("错误等级：")) {
                            log.info("DeepSeek-GF 纠正结果不包含\"输出：\"\"分类：\"\"错误等级：\"\"来源：\"，跳过本次纠正");
                            return null;
                        }
                        return this.formatResponse(message.getContent(), text);
                    }
                }
            }
            return null;
        } catch (HttpStatusCodeException e) {
            log.error("DEEPSEEK API请求失败，错误信息", e);
            log.error("DEEPSEEK API请求失败，错误信息：{}", e.getMessage());
            return null;
        }
    }
}
